﻿using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class FoodSpawner : NetworkBehaviour {
    // this module is server-only

    public static FoodSpawner _instance;
    public static FoodSpawner Instance {
        get {return _instance;}
    }

    public GameObject foodPrefab;

    public int numOfFood;

    // Use this for initialization
    void Start() {
        // set to instance
        _instance = this;
        // generate food
        for (; numOfFood > 0; numOfFood --) {
            createARandomFood();
        }
    }

    // Update is called once per frame
    void Update() {
        // Debug.Log("food spawner update");
        if (numOfFood > 0) {
            createARandomFood();
            numOfFood --;
        }
    }

    // called by others, check if it is in the server
    public void addAFoodToQueue() {
        if (!isServer) return;
        numOfFood ++;
    }

    void createARandomFood() {
        var p = new Vector3(Random.Range(-8.0f, 8.0f),
                            Random.Range(-8.0f, 8.0f), 0);
        var enemy = (GameObject)Instantiate(foodPrefab, p, Quaternion.identity);
        NetworkServer.Spawn(enemy);
    }
}
